package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    static final String KEY_PREFIX = "user:code:phone:";
    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    //用户名手机唯一性校验
    public Boolean checkUserData(String data, Integer type) {
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }
        return userMapper.selectCount(user) != 1;
    }

    //发送验证码
    public Boolean sendVerifyCode(String phone) {
        //生成随机验证码
        String code = NumberUtils.generateCode(6);
        //发送验证码
        try {
            Map<String, Object> msgMap = new HashMap<>();
            msgMap.put("phone", phone);
            msgMap.put("code", code);
            //通知sms服务发送验证码
            amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msgMap);
            //将验证码存入redis并缓存5分钟
            redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5L, TimeUnit.MINUTES);
            return true;
        } catch (AmqpException e) {
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }

    //用户注册
    public Boolean register(User user, String code) {
        //从redis中取出验证码
        String codeCache = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (StringUtils.isBlank(code) || !code.equals(codeCache)) {
            return false;
        }
        user.setCreated(new Date());//设置创建时间
        //生成盐值
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //对密码进行加密存储
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        boolean boo = this.userMapper.insertSelective(user) == 1;
        if (boo) {
            try {
                redisTemplate.delete(KEY_PREFIX + user.getPhone());//删除redis中的key
            } catch (Exception e) {

            }
        }
        return boo;
    }

    public User queryUser(String username, String password) {
        User record = new User();
        record.setUsername(username);
        //检测用户名
        User user = this.userMapper.selectOne(record); //数据库查出来的user
        if (user == null) {
            return null;
        }
        //对前端密码进行加密
        String entryPwd = CodecUtils.md5Hex(password, user.getSalt());
        //加密密码比对
        if (!entryPwd.equals(user.getPassword())) {
            return null;
        }
        // 用户名密码都正确
        return user;

    }
}
